<?php
defined('_JEXEC') or die();

class WrdControllerProducts extends JControllerLegacy {
	
	function __construct( $default = array()){
    		parent::__construct( $default );
	}

	function display()
	{
		switch($this->getTask()){
			case 'add':{
					JRequest::setVar( 'hidemainmenu', 1 );
					JRequest::setVar( 'layout', 'form'  );
					JRequest::setVar( 'view'  , 'products');
				} 
				break;
            default:
				JRequest::setVar( 'view'  , 'products');
            	break;
		}
		parent::display();
	}
        
	//save profile info
	function save(){
		$params = JComponentHelper::getParams('com_wrd');
		
       	$post=JRequest::get('post');
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$post['created_date'] = date("Y-m-d H:i:s");
		
		
		if(isset($post['voucher']))
			 $post['voucher'] =1;
		else 
			$post['voucher'] = 0;
		if(intval($post['point']) == 0 &&
			intval($post['pointx']) == 0 &&
			intval($post['cash']) == 0
		)
		{
			$this->setRedirect('index.php?option=com_wrd&controller=products','Error Saved: Point = 0 Point & Cash = 0');
            return false;		
		}
		
		$user = JFactory::getUser();
       	$model=$this->getModel('products');
       	
       	$lang = new LanguagesModelInstalled();
       	$current_languages = $lang ->getData();
       	
       	$name_tmp_arr = array();
       	$des_tmp_arr = array();
       	foreach ($current_languages as $lang){
       		$name_tmp_arr[$lang->language] = JRequest::getVar('name_'.$lang->language);
       		$des_tmp_arr[$lang->language] = JRequest::getVar( 'des_'.$lang->language, '', 'post', 'string', JREQUEST_ALLOWHTML );
       	}
       	
       	
       	$post['name'] = serialize($name_tmp_arr);
       	$post['des'] = serialize($des_tmp_arr);
       	
        
        $id_category=$model->store($post,'products');
       	
       	if($id_category!=0){
       		$this->sendNoticeEmail($post);
			//update product_cost for vip_wrd_redemption_report
			$query = "UPDATE #__wrd_redemption_report SET product_cost = '".(int)$post['cost_pricing']."' WHERE product_id = '".$post['id']."'";
       		$db = JFactory::getDbo();
       		
			$db->setQuery($query);
       		$db->query();
			//save images
			$query = 'UPDATE #__wrd_file SET product_id = '.$id_category.' WHERE product_id = 0 AND user_id = '.$user->id;
       		$db = JFactory::getDbo();
       		$db->setQuery($query);
       		$db->query();
       		
			
       		//redirect
			$this->setRedirect('index.php?option=com_wrd&controller=products','Saved');
			return true;                
       	}
       	else{
            $this->setRedirect('index.php?option=com_wrd&controller=products','Error Saved');
            return false;
       	}
    }    
   
    function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to delete' ) );
		}

		$model = $this->getModel('products');
		if(!$model->delete($cid)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		$this->setRedirect( 'index.php?option=com_wrd&controller=products' );
	}
   
    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>' ) );
		}

		$model = $this->getModel('products');
		if(!$model->publish($cid, 1)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		$this->setRedirect( 'index.php?option=com_wrd&controller=products' );
	}

	function unpublish(){
		
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>'  ) );
		}

		$model = $this->getModel('products');
		
		if(!$model->publish($cid, 0)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		$this->setRedirect( 'index.php?option=com_wrd&controller=products' );
	}
	
	public function saveorder(){
		JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Get the arrays from the Request
		$order	= JRequest::getVar('order',	null, 'post', 'array');
		$originalOrder = explode(',', JRequest::getString('original_order_values'));
		parent::saveorder();
	}
	
	public function sendNoticeEmail($post){
		//current_product
		$user = &JFactory::getUser();
		$old_item = $user->current_product;
		$post['name'] = unserialize($post['name']);
		$mapping_key = array();
		$mapping_key['name_en-GB'] 			= 'Name En';
		$mapping_key['name_vi-VN'] 			= 'Name Vi';
		$mapping_key['p_code'] 				= 'Project Code';
		$mapping_key['point'] 				= 'Point';
		$mapping_key['pointx'] 				= 'Fash Track';
		$mapping_key['cash']		 		= 'Cash';
		$mapping_key['price'] 				= 'Price';
		$mapping_key['cost_pricing'] 		= 'Cost Pricing';
		$mapping_key['quantity'] 			= 'Quantity';
		$mapping_key['published_up'] 		= 'Published Up';
		$mapping_key['published_down'] 		= 'Published Down';
		$mapping_key['published'] 			= 'Published';
		
		$emailSubject =  'WMCVIP - The product has been created or modified - System report';
		
		$email	= array('truongnhan0311@gmail.com','dinh.chau@wmcvietnam.com' );
		$mailFrom = 'WMCVIP';
		
		$emailBody = '<p><b>User Name:</b>'.$user->name.'</p>';
		$emailBody .= '<p><b>User ID:</b>'.$user->id.'</p>';
		$emailBody .= '<p><b>User Emaili:</b>'.$user->email.'</p>';
		
		$emailBody .= '<table width="100%">';
		$emailBody .= '<table><tr><td></td><td><b>OLD VALUE</b></td><td><b>NEW VALUE</b></td></tr>';
		foreach ($mapping_key as $key => $value) {
			$emailBody .=	'<tr>';
			
 			if( $key == 'p_code'){
 				$emailBody .= 	'<td><b>'.$value.':</b></td>';
 				$emailBody .= 	'<td>'.WrdHelper::getProjectName($old_item->$key).'</td>';
 				$emailBody .= 	'<td>'.WrdHelper::getProjectName($post[$key]).'</td>';
 			}
 			elseif( $key == 'name_en-GB'){
 				$emailBody .= 	'<td><b>'.$value.':</b></td>';
 				$emailBody .= 	'<td>'.$old_item->name['en-GB'].'</td>';
 				$emailBody .= 	'<td>'.$post['name']['en-GB'].'</td>';
 			}elseif($key == 'name_vi-VN'){
 				$emailBody .= 	'<td><b>'.$value.':</b></td>';
 				$emailBody .= 	'<td>'.$old_item->name['vi-VN'].'</td>';
 				$emailBody .= 	'<td>'.$post['name']['vi-VN'].'</td>';
 			}
 			else{
 				$emailBody .=	'<tr>';
 				$emailBody .= 	'<td><b>'.$value.':</b></td>';
 				$emailBody .= 	'<td>'.$old_item->$key.'</td>';
 				$emailBody .= 	'<td>'.$post[$key].'</td>';
 			}
				
			$emailBody .=	'</tr>';
		}
		
		$emailBody .= '<table>';
		
		return JUtility::sendMail($mailFrom, 'WMCVIP', $email, $emailSubject, $emailBody,1);
	}
}